package com.atguigu.web;

import com.atguigu.pojo.User;
import com.atguigu.service.BookService;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;
import com.atguigu.utils.WebUtils;
import com.google.gson.Gson;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = userService.login(new User(null, username, password, null));
        if (user == null) {
//          把错误信息，和回显表单信息，保存到Request域中
            req.setAttribute("msg", "用户名或密码错误");
            req.setAttribute("username", username);

            System.out.println("用户名或密码错误");
//           跳回登陆页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        } else {
            /*将登录成功的回显信息保存到session域中*/
            req.getSession().setAttribute("user",user);
            System.out.println("登陆成功");
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        }


    }
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //     1.获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

String taken = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);

        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
      User user = WebUtils.copyParamToBean(req.getParameterMap(),new User());

//        2.检查验证码是否正确
        if (taken != null && taken.equalsIgnoreCase(code)) {
//        正确

            //        3.检查用户名是否可用
            if (userService.existUsername(username)) {

                req.setAttribute("msg","用户名已存在");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
                System.out.println("用户名" + username + "已存在");

//        跳回注册页面
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);

            } else {

                //        可用
                //        调用service保存数据库
                userService.registUser(new User(null, username, password, email));

                //          返回regist_success.html页面
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }


            //        不正确
        } else {

            req.setAttribute("msg","验证码不正确");
            System.out.println("验证码" +code+"不正确");

            //        跳回register.html页面
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");


        try {
            //        获取action鉴别字符串，获取相应的业务，方法反射对象
             Method method = this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
//             调用目标业务，方法
             method.invoke(this,req,resp);

        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
            e.printStackTrace();
        }

          /*  if ("login".equals(action)){
                login(req,resp);
            }else if ("regist".equals(action)){
                regist(req,resp);
            }
*/
    }

    protected void loginOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1.销毁session中用户登陆的信息
        req.getSession().invalidate();
//        2.重定向会首页
        resp.sendRedirect(req.getContextPath());
    }

    protected void getJsonServlet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
boolean existsusername = userService.existUsername(username);
        Map<String,Object> resultmap =new HashMap<>();
        resultmap.put("existsusername",existsusername);
        Gson gson = new Gson();
       String json = gson.toJson(resultmap);
        resp.getWriter().write(json);

    }
    }


